import { ref, computed } from "vue";

// 类型定义
// ======================================================

/**
 * 蓝牙设备类型接口定义
 */
export interface BluetoothDevice {
  /** 设备名称 */
  name: string;
  /** 设备ID */
  deviceId: string;
  /** 信号强度 */
  RSSI?: number;
}

/**
 * 蓝牙写入数据选项接口
 */
export interface WriteBLEDataOptions {
  /** 要写入的数据 */
  data?: ArrayBuffer;
  /** 服务ID */
  serviceId?: string;
  /** 写入特征值ID */
  characteristicId?: string;
  /** 通知特征值ID */
  notifyCharacteristicId?: string;
  /** 成功回调 */
  successCallback?: (res: any) => void;
  /** 失败回调 */
  failCallback?: (err: any) => void;
  /** 特征值变化回调 */
  valueChangeCallback: (value: string) => void;
  /** 开始扫描回调 */
  startScanCallback?: () => void;
}

/**
 * 操作回调函数类型
 */
type Callback = () => void;
type ErrorCallback = (error: any) => void;

// 常量定义
// ======================================================

/** 蓝牙服务UUID */
const SERVICE_UUID = "0000FFE0-0000-1000-8000-00805F9B34FB";
/** 写特征值UUID */
const WRITE_UUID = "0000FFE3-0000-1000-8000-00805F9B34FB";
/** 通知特征值UUID */
const NOTIFY_UUID = "0000FFE4-0000-1000-8000-00805F9B34FB";
/** 扫描超时时间(毫秒) */
const SCAN_TIMEOUT = 5000;
/** 设备列表获取延迟(毫秒) */
const DEVICE_LIST_DELAY = 2000;
/** 设备名称未知标识 */
const UNKNOWN_DEVICE = "未知设备";
/** 默认消息提示持续时间 */
const DEFAULT_TOAST_DURATION = 3000;
/** 缓存的蓝牙列表 key */
const CACHED_BLUETOOTH_DEVICES = "BT_CACHED_DEVICES";

// 蓝牙值监听回调函数
/** ；蓝牙扫描值回调 */
let lastValueChangeCallback: ((value: string) => void) | null = null;
/** notify启动失败回调 */
let notifyFailCallback: ((error: any) => void) | undefined = undefined;

// 全局共享状态
// ======================================================

/** 当前连接的设备 */
const connectedDevice = ref<BluetoothDevice | null>(null);
/** 是否正在扫描 */
const isScanning = ref(false);
// ** 蓝牙是否可用 */
const available = ref(false);

const PRESET_VALUE = 0xffff;
const POLYNOMIAL = 0x8408;

/**
 * 蓝牙发送数据
 * @returns
 */
export function useSendBLEData() {
  /**
   * 停止蓝牙扫描
   */
  const stopBluetoothScan = (options: WriteBLEDataOptions) => {
    writeBLEData({ ...options, data: generateBufferByStop() });
  };


  /**
   * 写入蓝牙数据
   * @param options - 写入选项
   */
  const writeBLEData = async (options: WriteBLEDataOptions) => {
    const {
      data = generateBufferByScance(),
      serviceId = SERVICE_UUID,
      characteristicId = WRITE_UUID,
      successCallback,
      failCallback,
      valueChangeCallback,
      startScanCallback,
    } = options;

    if (typeof startScanCallback === "function") {
      startScanCallback();
    }

    // 检查是否已连接设备
    if (!connectedDevice.value) {
      const error = new Error("没有已连接的蓝牙设备");
      showToast("请先连接蓝牙设备");

      if (typeof failCallback === "function") {
        failCallback(error);
      }
      return;
    }

    lastValueChangeCallback = valueChangeCallback;
    notifyFailCallback = failCallback;

    // 检查蓝牙是否可用
    if (!available.value) {
      showToast("蓝牙不可用，请重连蓝牙设备", "error");
      const error = new Error("蓝牙不可用，请检查设备蓝牙状态");
      if (typeof failCallback === "function") {
        failCallback(error);
      }
      return;
    }

    uni.writeBLECharacteristicValue({
      deviceId: connectedDevice.value.deviceId,
      serviceId,
      characteristicId: characteristicId,
      value: data,
      success: (res) => {
        if (typeof successCallback === "function") {
          successCallback(res);
        }
      },
      fail: (err) => {
        showToast("写入数据失败");
        if (typeof failCallback === "function") {
          failCallback(err);
        }
      },
    });
  };

  // 公共访问方法
  // ======================================================
  /**
   * 获取蓝牙服务UUID
   * @returns 蓝牙服务UUID
   */
  function getServiceUUID(): string {
    return SERVICE_UUID;
  }

  /**
   * 获取写特征值UUID
   * @returns 写特征值UUID
   */
  function getWriteUUID(): string {
    return WRITE_UUID;
  }

  /**
   * 获取通知特征值UUID
   * @returns 通知特征值UUID
   */
  function getNotifyUUID(): string {
    return NOTIFY_UUID;
  }

  /**
   * 获取当前连接的设备
   * @returns 当前连接的设备，如无则返回null
   */
  function getCurrentDevice(): BluetoothDevice | null {
    return connectedDevice.value;
  }

  /**
   * 获取当前连接设备的ID
   * @returns 当前连接设备的ID，如无则返回null
   */
  function getCurrentDeviceId(): string | null {
    return connectedDevice.value ? connectedDevice.value.deviceId : null;
  }

  /**
   * 检查是否有连接的设备
   * @returns 是否有设备连接
   */
  function hasConnectedDevice(): boolean {
    return connectedDevice.value !== null;
  }

  /**
   * 生成默认的蓝牙数据缓冲区
   * @returns 生成的ArrayBuffer
   */
  function generateBufferByScance(): ArrayBuffer {
    let buffer = new ArrayBuffer(12);
    let dataView = new DataView(buffer);
    dataView.setUint8(0, parseInt("0xCF", 16));
    dataView.setUint8(1, parseInt("0xFF", 16));
    dataView.setUint16(2, parseInt("0x0001", 16));
    dataView.setUint8(4, parseInt("0x05", 16));
    dataView.setUint8(5, parseInt("0x00", 16));
    dataView.setUint32(6, parseInt("0x00000000", 16));
    let arr = [
      parseInt("0xCF", 16),
      parseInt("0xFF", 16),
      parseInt("0x00", 16),
      parseInt("0x01", 16),
      parseInt("0x05", 16),
      parseInt("0x00", 16),
      parseInt("0x00", 16),
      parseInt("0x00", 16),
      parseInt("0x00", 16),
      parseInt("0x00", 16),
    ];
    dataView.setUint16(10, uiCrc16Cal(arr, arr.length));
    return buffer;
  }

  /**
   *生成停止扫描的蓝牙数据缓冲区
   * @returns
   */
  function generateBufferByStop(): ArrayBuffer {
    let buffer = new ArrayBuffer(7);
    let dataView = new DataView(buffer);
    dataView.setUint8(0, parseInt("0xCF", 16));
    dataView.setUint8(1, parseInt("0xFF", 16));
    dataView.setUint16(2, parseInt("0x0002", 16));
    dataView.setUint8(4, parseInt("0x00", 16));
    let arr = [
      parseInt("0xCF", 16),
      parseInt("0xFF", 16),
      parseInt("0x00", 16),
      parseInt("0x02", 16),
      parseInt("0x00", 16),
    ];
    dataView.setUint16(5, uiCrc16Cal(arr, arr.length));
    return buffer;
  }

  /**
   * 计算CRC16校验值
   * @param data - 数据数组
   * @param length - 数据长度
   * @returns CRC16校验值
   */

  function uiCrc16Cal(pucY, ucX) {
    let uiCrcValue = PRESET_VALUE;

    for (let ucI = 0; ucI < ucX; ucI++) {
      uiCrcValue ^= pucY[ucI];

      for (let ucJ = 0; ucJ < 8; ucJ++) {
        if (uiCrcValue & 0x0001) {
          uiCrcValue = (uiCrcValue >> 1) ^ POLYNOMIAL;
        } else {
          uiCrcValue = uiCrcValue >> 1;
        }
      }
    }

    return uiCrcValue;
  }

  return {
    writeBLEData,
    stopBluetoothScan,
    getServiceUUID,
    getWriteUUID,
    getNotifyUUID,
    getCurrentDevice,
    getCurrentDeviceId,
    hasConnectedDevice,
  };
}

/**
 * 蓝牙操作hook函数
 * 提供蓝牙设备的扫描、连接、断开等操作
 */
export function useBluetooth() {
  /** 扫描到的设备列表 */
  const devices = ref<BluetoothDevice[]>([]);
  // 适配器初始化状态
  const adapterStatus = ref(false);

  // 计算属性
  // ======================================================
  /**
   * 获取所有设备列表
   */
  const allDevices = computed(() => devices.value);

  // 蓝牙基础操作
  // ======================================================

  /**
   * 检查设备是否已连接
   * @param device - 要检查的设备
   * @returns 设备是否已连接
   */
  const isDeviceConnected = (device: BluetoothDevice): boolean => {
    return (
      connectedDevice.value !== null &&
      connectedDevice.value.deviceId === device.deviceId
    );
  };

  /**
   * 初始化蓝牙适配器
   * @param successCallback - 成功回调
   * @param failCallback - 失败回调
   */
  const initBluetooth = (
    successCallback?: Callback,
    failCallback?: ErrorCallback
  ): void => {
    uni.openBluetoothAdapter({
      success: () => {
        adapterStatus.value = true;
        // 开始扫描蓝牙设备
        startBluetoothDevicesDiscovery();
        // // 监听蓝牙适配器状态变化
        listenBluetoothAdapterStateChange();
        // // 监听蓝牙设备连接状态变化
        listenBLEConnectionStateChange();
        // 延迟获取蓝牙设备列表，确保有足够时间扫描到设备
        setTimeout(() => {
          getBluetoothDevices();
          // 初始化成功后执行回调
          if (typeof successCallback === "function") {
            successCallback();
          }
        }, DEVICE_LIST_DELAY);
      },
      fail: (err) => {
        adapterStatus.value = false;
        // 初始化失败后执行回调
        if (typeof failCallback === "function") {
          failCallback(err);
        }
      },
    });
  };

  /**
   * 获取已发现的蓝牙设备
   */
  const getBluetoothDevices = (): void => {
    uni.getBluetoothDevices({
      success: async (res) => {
        if (res.devices && res.devices.length > 0) {
          // 过滤无效设备并格式化
          const validDevices = res.devices
            .filter(isValidDevice)
            .map((device: any) => ({
              name: device.name || device.localName,
              deviceId: device.deviceId,
              RSSI: device.RSSI,
            }));
          const cachedDevice = await getStorageByBluetooth();
          /**
           * 注意：这里的 cachedDevice 是从本地存储获取的设备列表
           * 需要与当前扫描到的设备列表进行合并
           * 过滤掉已存在的设备,只保留未缓存的设备,只保留未缓存的设备,这样可以避免重复添加已连接的设备
           * getBluetoothDevices获取到和缓存一样的蓝牙，这里取的缓存，过滤到查询到的蓝牙，是因为查询的蓝牙可能没有RSSI
           */

          /**
           * 注意：缓存的目前是解决小程序无法获取到已连接设备的问题
           */

          const matchDevice = validDevices.filter((k) => {
            const exists = cachedDevice.some(
              (item) => item.deviceId === k.deviceId
            );
            return !exists;
          });

          devices.value = matchDevice.concat(cachedDevice);
          devices.value = devices.value.filter((k) =>
            isValidDeviceName(k.name)
          );

          // 对设备列表进行排序
          sortDeviceList();
        }
      },
      fail: (err) => {
        showToast("获取蓝牙设备列表失败", "error");
      },
    });
  };

  /**
   * 监听蓝牙适配器状态变化
   */
  const listenBluetoothAdapterStateChange = (): void => {
    uni.onBluetoothAdapterStateChange((res) => {
      available.value = res.available;
      if (!res.available) {
        // 蓝牙不可用时清空设备列表
        devices.value = [];
        connectedDevice.value = null;
        showToast("蓝牙已关闭", "none");
      } else if (res.available && res.discovering) {
        // 蓝牙可用且正在搜索
        isScanning.value = true;
      } else if (res.available && !res.discovering) {
        // 蓝牙可用但停止搜索
        isScanning.value = false;
      }
    });
  };

  /**
   * 监听蓝牙设备连接状态变化
   */
  const listenBLEConnectionStateChange = (): void => {
    uni.onBLEConnectionStateChange((res) => {
      // 更新连接状态
      if (
        !res.connected &&
        connectedDevice.value &&
        res.deviceId === connectedDevice.value.deviceId
      ) {
        showToast("蓝牙连接已断开");
        connectedDevice.value = null;
      }
    });
  };

  // 设备扫描相关
  // ======================================================

  /**
   * 开始扫描蓝牙设备
   */
  const startBluetoothDevicesDiscovery = (): void => {
    if (isScanning.value) {
      return;
    }
    isScanning.value = true;
    uni.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false, // 不允许重复上报同一设备
      interval: 0, // 默认的上报间隔
      success: () => {
        // 监听寻找到新设备的事件
        onBluetoothDeviceFound();
        // 自动停止扫描
        setTimeout(() => {
          stopBluetoothDevicesDiscovery();
        }, SCAN_TIMEOUT);
      },
      fail: (err) => {
        showToast("扫描失败", "error");
        isScanning.value = false;
      },
    });
  };

  /**
   * 监听寻找到新设备的事件
   */
  const onBluetoothDeviceFound = (): void => {
    uni.onBluetoothDeviceFound((res) => {
      res.devices.forEach((device) => {
        // 过滤无效设备
        if (!isValidDevice(device)) return;

        if (!isValidDeviceName(device.name)) return;

        // 构建设备对象
        const newDevice: BluetoothDevice = {
          name: device.name || device.localName,
          deviceId: device.deviceId,
          RSSI: device.RSSI,
        };

        // 检查是否已存在于列表中
        const idx = devices.value.findIndex(
          (item) => item.deviceId === device.deviceId
        );

        if (idx === -1) {
          // 不存在则添加
          devices.value.push(newDevice);
        } else {
          // 已存在则更新
          devices.value[idx] = newDevice;
        }
      });

      // 对设备列表进行排序
      sortDeviceList();
    });
  };

  const isValidDeviceName = (name: string | undefined): boolean => {
    // 判断 name 是否存在
    return !!name
  };

  /**
   * 对设备列表进行排序
   * 排序规则：已连接 > 信号强度
   */
  const sortDeviceList = (): void => {
    devices.value.sort((a, b) => {
      // 已连接设备优先
      if (isDeviceConnected(a) && !isDeviceConnected(b)) return -1;
      if (!isDeviceConnected(a) && isDeviceConnected(b)) return 1;

      // 有RSSI的设备比没有RSSI的设备优先
      if (a.RSSI && !b.RSSI) return -1;
      if (!a.RSSI && b.RSSI) return 1;

      // 按信号强度排序（信号强度大的排前面）
      if (a.RSSI && b.RSSI) return b.RSSI - a.RSSI;

      return 0;
    });
  };

  /**
   * 停止扫描蓝牙设备
   * @param successCallback - 成功回调
   */
  const stopBluetoothDevicesDiscovery = (successCallback?: Callback): void => {
    if (!isScanning.value) {
      if (typeof successCallback === "function") {
        successCallback();
      }
      return;
    }

    uni.stopBluetoothDevicesDiscovery({
      success: () => {
        isScanning.value = false;
        if (typeof successCallback === "function") {
          successCallback();
        }
      },
      fail: (err) => {
        console.error("停止扫描蓝牙设备失败:", err);
      },
      complete: () => {
        isScanning.value = false;
      },
    });
  };

  // 设备连接相关
  // ======================================================

  /**
   * 连接蓝牙设备
   * @param device - 要连接的设备
   */
  const connectDevice = (device: BluetoothDevice): void => {
    // 如果已经连接该设备，则不重复连接
    if (
      connectedDevice.value &&
      connectedDevice.value.deviceId === device.deviceId
    ) {
      showToast("设备已连接");
      return;
    }

    // 先断开已连接的设备
    if (connectedDevice.value) {
      disconnectDevice(connectedDevice.value, () => {
        doConnectDevice(device);
      });
    } else {
      doConnectDevice(device);
    }
  };

  /**
   * 执行连接设备操作
   * @param device - 要连接的设备
   */
  const doConnectDevice = (device: BluetoothDevice): void => {
    uni.showLoading({
      title: "正在连接...",
    });

    uni.createBLEConnection({
      deviceId: device.deviceId,
      success: async () => {
        connectedDevice.value = device;
        saveBluetoothDevice(device);
        const { services }: any = await getBLEDeviceServices();
        if (services && Array.isArray(services) && services.length > 0) {
          const targetService = services.find(
            (item: { uuid: string }) => item.uuid === SERVICE_UUID
          );
          /**
           * 注意：这里的targetService是从设备服务列表中获取的
           * 可以直接使用targetService.uuid， 目前我这里是写死的，可以直接修改
           * SERVICE_UUID = targetService.uuid，就是设备的服务UUID
           */
          if (targetService) {
            // 设置MTU并获取特征值
            setDeviceMTU();
            /**
             * 注意：这里的getBLEDeviceCharacteristics是获取设备特征值
             * 可以根据返回值 更新 WRITE_UUID 和 NOTIFY_UUID
             */
            await getBLEDeviceCharacteristics();
            notifyBLECharacteristicValueChange();
          } else {
            showToast("当前连接:非背夹式读卡器设备");
          }
        }
        uni.hideLoading();
        showToast("连接成功", "success");
        // 先启用特征值变化通知
      },
      fail: (err) => {
        uni.hideLoading();
        showToast("连接设备失败", "error");
      },
    });
  };

  const notifyBLECharacteristicValueChange = () => {
    uni.notifyBLECharacteristicValueChange({
      deviceId: connectedDevice.value.deviceId,
      serviceId: SERVICE_UUID,
      characteristicId: NOTIFY_UUID,
      state: true,
      success: () => {
        // 监听特征值变化
        uni.onBLECharacteristicValueChange((result) => {
          if (typeof lastValueChangeCallback === "function") {
            const hexData = ab2hex(result.value);
            lastValueChangeCallback(hexData)
          }
        });
      },
      fail: (err) => {
        showToast("启用通知失败", "error");
        if (typeof notifyFailCallback === "function") {
          notifyFailCallback(err);
        }
      },
    });
  };

  /**
   * 获取蓝牙设备特征值
   */
  const getBLEDeviceCharacteristics = () => {
    if (!connectedDevice.value) return;
    return new Promise((resolve, reject) => {
      uni.getBLEDeviceCharacteristics({
        deviceId: connectedDevice.value.deviceId,
        serviceId: SERVICE_UUID,
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          resolve(err);
          showToast("获取特征值失败", "error");
        },
      });
    });
  };

  /**
   * 设置设备MTU值
   */
  const setDeviceMTU = (): void => {
    if (!connectedDevice.value) return;

    uni.setBLEMTU({
      deviceId: connectedDevice.value.deviceId,
      mtu: 512,
      success: () => {
        console.log("MTU设置成功");
      },
      fail: (err) => {
        console.error("MTU设置失败:", err);
      },
    });
  };

  /**
   * 获取蓝牙设备的服务
   * @param successCallback - 成功回调
   * @param failCallback - 失败回调
   */
  const getBLEDeviceServices = () => {
    return new Promise((resolve, reject) => {
      if (!connectedDevice.value) {
        const err = new Error("没有已连接的设备");
        reject(err);
      }
      uni.getBLEDeviceServices({
        deviceId: connectedDevice.value.deviceId,
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  };

  /**
   * 断开蓝牙设备连接
   * @param device - 要断开的设备
   * @param callback - 操作完成回调
   */
  const disconnectDevice = (
    device: BluetoothDevice,
    callback?: Callback
  ): void => {
    uni.showLoading({
      title: "断开连接中...",
    });

    uni.closeBLEConnection({
      deviceId: device.deviceId,
      success: () => {
        if (
          connectedDevice.value &&
          connectedDevice.value.deviceId === device.deviceId
        ) {
          connectedDevice.value = null;
        }

        showToast("已断开连接", "success");

        if (typeof callback === "function") {
          callback();
        }
      },
      fail: (err) => {
        showToast("断开连接失败", "error");
      },
      complete: () => {
        uni.hideLoading();
      },
    });
  };

  /**
   * 关闭蓝牙适配器
   */
  const closeBluetoothAdapter = (): void => {
    uni.closeBluetoothAdapter({
      success: () => {
        devices.value = [];
        connectedDevice.value = null;
        showToast("蓝牙适配器已关闭");
      },
      fail: (err) => {
        console.error("关闭蓝牙适配器失败", err);
      },
    });
  };

  /**
   * 保存蓝牙设备信息到本地存储,缓存的目的在于，已经连接手机的蓝牙，小程序无法获取到
   * @param device - 要保存的蓝牙设备
   */
  const saveBluetoothDevice = (device: BluetoothDevice) => {
    let deviceInfo = uni.getStorageSync(CACHED_BLUETOOTH_DEVICES) || [];
    if (!Array.isArray(deviceInfo)) {
      deviceInfo = [];
    }
    const exists = deviceInfo.some(
      (item) => item.deviceId === device.deviceId
    );
    if (!exists && device.deviceId) {
      deviceInfo.push(device);
      uni.setStorageSync(CACHED_BLUETOOTH_DEVICES, deviceInfo);
    }
  };

  /**
   * 从本地存储获取蓝牙设备信息
   * @returns 存储的蓝牙设备列表
   */
  const getStorageByBluetooth = (): BluetoothDevice[] => {
    const deviceInfo = uni.getStorageSync(CACHED_BLUETOOTH_DEVICES);
    if (deviceInfo && Array.isArray(deviceInfo)) {
      return removeDuplicatesById(deviceInfo);
    } else if (deviceInfo && typeof deviceInfo === "object") {
      return [deviceInfo];
    }
    return [];
  };

  /**
   * 去重，根据deviceId或id属性，为了兼容老版本缓存的id
   */
  const removeDuplicatesById = <T extends { deviceId?: string; }>(
    array: T[]
  ): T[] => {
    const seen = new Set<string>();
    return array.filter((item) => {
      const uniqueId = item.deviceId; // 使用 deviceId 或 id 作为唯一标识
      if (uniqueId && !seen.has(uniqueId)) {
        seen.add(uniqueId);
        return true;
      }
      return false;
    });
  };

  // 用户交互相关
  // ======================================================

  /**
   * 处理设备点击
   * @param device - 被点击的设备
   */
  const handleDeviceClick = (device: BluetoothDevice): void => {
    if (!adapterStatus.value) {
      initialize(
        () => {
          handleDeviceConnection(device);
        },
        () => {
          showToast("请打开蓝牙", "error");
        }
      );
      return;
    }
    handleDeviceConnection(device);
  };

  /**
   *  处理设备连接
   * @param device
   * @returns
   */
  const handleDeviceConnection = (device: BluetoothDevice) => {
    // 如果已连接则断开，否则连接
    if (isDeviceConnected(device)) {
      disconnectDevice(device);
      return;
    }

    // 如果正在扫描，先停止扫描
    if (isScanning.value) {
      stopBluetoothDevicesDiscovery(() => {
        connectDevice(device);
      });
      return;
    }

    connectDevice(device);
  };

  /**
   * 刷新设备列表
   */
  const refreshDeviceList = (): void => {
    // 如果正在扫描，先停止扫描
    if (isScanning.value) {
      stopBluetoothDevicesDiscovery(() => {
        startBluetoothDevicesDiscovery();
        if (devices.value.length === 0) {
          setTimeout(() => {
            getBluetoothDevices();
          }, DEVICE_LIST_DELAY);
        }
      });
      return;
    }
    startBluetoothDevicesDiscovery();
    if (devices.value.length === 0) {
      setTimeout(() => {
        getBluetoothDevices();
      }, DEVICE_LIST_DELAY);
    }
  };

  // 生命周期相关
  // ======================================================

  /**
   * 初始化蓝牙功能
   * @param successCallback - 成功回调
   * @param failCallback - 失败回调
   */
  const initialize = (
    successCallback?: Callback,
    failCallback?: ErrorCallback
  ): void => {
    initBluetooth(successCallback, failCallback);
  };

  /**
   * 释放蓝牙资源
   * @param successCallback - 成功回调
   * @param failCallback - 失败回调
   */
  const uninitialize = (
    successCallback?: Callback,
    failCallback?: ErrorCallback
  ): void => {
    try {
      // 停止扫描和断开连接
      stopBluetoothDevicesDiscovery();
      closeBluetoothAdapter();

      // 执行成功回调
      if (typeof successCallback === "function") {
        successCallback();
      }
    } catch (error) {
      console.error("蓝牙资源释放失败", error);
      // 执行失败回调
      if (typeof failCallback === "function") {
        failCallback(error);
      }
    }
  };
  /**
   * 将ArrayBuffer转换为16进制字符串
   * @param buffer - 要转换的ArrayBuffer
   * @returns 16进制字符串
   */
  function ab2hex(buffer: ArrayBuffer): string {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ("00" + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join("");
  }

  /**
   * 是否为有效设备（具有有效名称）
   * @param device - 设备对象
   * @returns 是否为有效设备
   */
  function isValidDevice(device: any): boolean {
    if (!device) return false;

    // 检查设备是否有有效名称
    if (device.name && device.name !== UNKNOWN_DEVICE) return true;
    if (device.localName && device.localName !== UNKNOWN_DEVICE) return true;

    return false;
  }

  // 返回公共API
  return {
    // 状态
    devices,
    connectedDevice,
    isScanning,
    allDevices,

    // 基础设备操作
    isDeviceConnected,
    initBluetooth,
    startBluetoothDevicesDiscovery,
    stopBluetoothDevicesDiscovery,
    connectDevice,
    disconnectDevice,

    // 用户交互
    handleDeviceClick,
    refreshDeviceList,

    // 生命周期管理
    initialize,
    uninitialize,
  };
}

/**
 * 显示统一格式的消息提示
 * @param message - 消息内容
 * @param type - 消息类型，默认为none
 * @param duration - 显示时长，默认为2000ms
 */
function showToast(
  message: string,
  type: "none" | "success" | "error" = "none",
  duration: number = DEFAULT_TOAST_DURATION
): void {
  uni.showToast({
    title: message,
    icon: type,
    duration: duration,
  });
}
